package com.reggie.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.reggie.acl.dataobject.Dish;
import com.reggie.acl.dataobject.Setmeal;
import com.reggie.acl.dataobject.ShoppingCart;
import com.reggie.acl.mapper.ShoppingCartMapper;
import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.service.model.bo.DishBO;
import com.reggie.service.service.DishService;
import com.reggie.service.service.SetmealService;
import com.reggie.service.service.ShoppingCartService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author yth
 * @since 2023-02-04
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 添加菜品到购物车
     *
     * @param shoppingCart 菜品购买信息
     * @return 数据
     */
    private ShoppingCart addDish2DB(ShoppingCart shoppingCart) {
        long dishId = shoppingCart.getDishId();
        long userId = shoppingCart.getUserId();
        // 获取菜品单价
        BigDecimal price = dishService.getById(dishId, 1)
                .map(Dish::getPrice)
                .orElseThrow(() -> new ReggieException(ResponseCode.CLIENT_ERROR, "菜品信息已过期，请重试"));
        // 判断是添加还是更新数量
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class);
        wrapper.eq(ShoppingCart::getDishId, dishId)
                .eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(wrapper);

        ShoppingCart updateCart = null;
        String dishFlavor1 = shoppingCart.getDishFlavor();
        for (ShoppingCart cart : shoppingCarts) {
            String dishFlavor2 = cart.getDishFlavor();
            if (StringUtils.isBlank(dishFlavor1) && StringUtils.isBlank(dishFlavor2)
                    || dishFlavor1 != null && dishFlavor1.equals(dishFlavor2)) {
                updateCart = cart;
                break;
            }
        }

        if (updateCart == null) {
            // 添加
            shoppingCart.setNumber(1);
            // 单价的存储是原价*100，所以amount = price / 100
            shoppingCart.setAmount(price.divide(new BigDecimal(100)));
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        } else {
            // 更新数量，单价时时刷新
            int number = updateCart.getNumber() + 1;
            updateCart.setNumber(number);
            // 单价的存储是原价*100，所以amount = price / 100
            BigDecimal amount = price.divide(new BigDecimal(100));
            updateCart.setAmount(amount);
            shoppingCartMapper.updateById(updateCart);
            return updateCart;
        }
    }

    /**
     * 添加套餐到购物车
     *
     * @param shoppingCart 套餐购买信息
     * @return 数据
     */
    private ShoppingCart addSetmeal2DB(ShoppingCart shoppingCart) {
        long setmealId = shoppingCart.getSetmealId();
        long userId = shoppingCart.getUserId();
        // 获取套餐单价
        BigDecimal price = setmealService.getById(setmealId, 1)
                .map(Setmeal::getPrice)
                .orElseThrow(() -> new ReggieException(ResponseCode.CLIENT_ERROR, "套餐信息已过期，请重试"));
        // 判断是添加还是更新数量
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class);
        wrapper.eq(ShoppingCart::getSetmealId, setmealId)
                .eq(ShoppingCart::getUserId, userId);
        ShoppingCart updateCart = shoppingCartMapper.selectOne(wrapper);

        if (updateCart == null) {
            // 添加
            shoppingCart.setNumber(1);
            // 单价的存储是原价*100，所以amount = price / 100
            shoppingCart.setAmount(price.divide(new BigDecimal(100)));
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        } else {
            // 更新数量，单价时时刷新
            int number = updateCart.getNumber() + 1;
            updateCart.setNumber(number);
            // 单价的存储是原价*100，所以amount = price / 100
            BigDecimal amount = price.divide(new BigDecimal(100));
            updateCart.setAmount(amount);
            shoppingCartMapper.updateById(updateCart);
            return updateCart;
        }
    }

    @Override
    public List<ShoppingCart> listByUserId(long userId) {
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class);
        wrapper.eq(ShoppingCart::getUserId, userId)
                .orderByDesc(ShoppingCart::getCreateTime);
        return shoppingCartMapper.selectList(wrapper);
    }

    @Override
    public ShoppingCart saveShoppingCart(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        if (dishId != null && setmealId == null) {
            // 添加的是菜品
            return this.addDish2DB(shoppingCart);
        } else {
            // 添加的是套餐
            return this.addSetmeal2DB(shoppingCart);
        }
    }

    @Override
    public void clean(long userId) {
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(wrapper);
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart, int decNumber) {
        Long id = shoppingCart.getId();
        if (id != null) {
            // 在购物车中按“-”按钮
            ShoppingCart byId = shoppingCartMapper.selectById(id);
            Integer number = byId.getNumber();
            if (number <= decNumber) {
                shoppingCartMapper.deleteById(id);
                return null;
            }
            byId.setNumber(number - decNumber);
            shoppingCartMapper.updateById(byId);
            return byId;
        }
        // 在菜单中按“-”按钮
        long userId = shoppingCart.getUserId();
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId)
                .eq(dishId != null, ShoppingCart::getDishId, dishId)
                .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        ShoppingCart one = shoppingCartMapper.selectOne(wrapper);
        Integer number = one.getNumber();
        if (number == 1) {
            shoppingCartMapper.deleteById(id);
            return null;
        }
        one.setNumber(number - 1);
        shoppingCartMapper.updateById(one);
        return one;
    }

    @Override
    public void removeByUserId(long userId) {
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class);
        wrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(wrapper);
    }

    @Override
    public void updateDish(DishBO dishBO) {
        LambdaUpdateWrapper<ShoppingCart> wrapper = Wrappers.lambdaUpdate(ShoppingCart.class)
                .eq(ShoppingCart::getDishId, dishBO.getId())
                .set(ShoppingCart::getName, dishBO.getName())
                .set(ShoppingCart::getImage, dishBO.getImage())
                .set(ShoppingCart::getAmount, dishBO.getPrice());
        shoppingCartMapper.update(new ShoppingCart(), wrapper);
    }
}
